import 'dart:io';

import 'package:country_code_picker/country_code_picker.dart';
import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/response_model.dart';
import 'package:efood_multivendor/data/model/response/userinfo_model.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_image.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/base/custom_text_field.dart';
import 'package:efood_multivendor/view/base/my_text_field.dart';
import 'package:efood_multivendor/view/base/not_logged_in_screen.dart';
import 'package:efood_multivendor/view/screens/auth/widget/code_picker_widget.dart';
import 'package:efood_multivendor/view/screens/profile/widget/profile_bg_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:phone_number/phone_number.dart';

class UpdateProfileScreen extends StatefulWidget {
  @override
  State<UpdateProfileScreen> createState() => _UpdateProfileScreenState();
}

class _UpdateProfileScreenState extends State<UpdateProfileScreen> {
  final FocusNode _firstNameFocus = FocusNode();
  final FocusNode _lastNameFocus = FocusNode();
  final FocusNode _phoneFocus = FocusNode();
  final FocusNode _alternativePhoneFocus = FocusNode();
  final TextEditingController _firstNameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _alternativePhoneController =
      TextEditingController();
  String? _countryDialCode;
  bool _isLoggedIn = false;

  @override
  void initState() {
    super.initState();

    _isLoggedIn = Get.find<AuthController>().isLoggedIn();
    if (_isLoggedIn && Get.find<UserController>().userInfoModel == null) {
      Get.find<UserController>().getUserInfo();
    }
    _countryDialCode =
        Get.find<AuthController>().getUserCountryCode().isNotEmpty
            ? Get.find<AuthController>().getUserCountryCode()
            : CountryCode.fromCountryCode(
                    Get.find<SplashController>().configModel?.country ?? '')
                .dialCode;
    Get.find<UserController>().initData();
  }

  String? removeCountryCode(String? phoneNumber) {
    // Check if the phone number starts with '+251'
    if (phoneNumber?.startsWith('+251') == true) {
      // Remove the first occurrence of '+251'
      return phoneNumber!.replaceFirst('+251', '');
    }
    // Return the original phone number if it doesn't start with '+251'
    return phoneNumber;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).cardColor,
      body: GetBuilder<UserController>(builder: (userController) {
        if (userController.userInfoModel != null &&
            _phoneController.text.isEmpty) {
          _firstNameController.text = userController.userInfoModel?.fName ?? '';

          _phoneController.text = userController.userInfoModel?.phone ?? '';
          _alternativePhoneController.text = removeCountryCode(
                  userController.userInfoModel?.alternativePhone) ??
              '';
        }

        return _isLoggedIn
            ? userController.userInfoModel != null
                ? SafeArea(
                    top: false,
                    child: ProfileBgWidget(
                      backButton: true,
                      circularImage: Center(
                          child: Stack(children: [
                        ClipOval(
                            child: userController.pickedFile != null
                                ? GetPlatform.isWeb
                                    ? Image.network(
                                        userController.pickedFile!.path,
                                        width: 100,
                                        height: 100,
                                        fit: BoxFit.cover,
                                      )
                                    : Image.file(
                                        File(userController.pickedFile!.path),
                                        width: 100,
                                        height: 100,
                                        fit: BoxFit.cover,
                                      )
                                : CustomImage(
                                    image:
                                        '${userController.userInfoModel!.image}',
                                    height: 100,
                                    width: 100,
                                    fit: BoxFit.cover,
                                  )),
                        Positioned(
                          bottom: 0,
                          right: 0,
                          top: 0,
                          left: 0,
                          child: InkWell(
                            onTap: () => userController.pickImage(),
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.black.withOpacity(0.3),
                                shape: BoxShape.circle,
                                border: Border.all(
                                    width: 1,
                                    color: Theme.of(context).primaryColor),
                              ),
                              child: Container(
                                margin: EdgeInsets.all(25),
                                decoration: BoxDecoration(
                                  border:
                                      Border.all(width: 2, color: Colors.white),
                                  shape: BoxShape.circle,
                                ),
                                child:
                                    Icon(Icons.camera_alt, color: Colors.white),
                              ),
                            ),
                          ),
                        ),
                      ])),
                      mainWidget: Column(children: [
                        Expanded(
                            child: Scrollbar(
                                child: SingleChildScrollView(
                          physics: BouncingScrollPhysics(),
                          padding:
                              EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                          child: Center(
                              child: SizedBox(
                                  width: Dimensions.WEB_MAX_WIDTH,
                                  child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          'first_name'.tr,
                                          style: sfRegular.copyWith(
                                              fontSize:
                                                  Dimensions.fontSizeSmall,
                                              color: Theme.of(context)
                                                  .disabledColor),
                                        ),
                                        SizedBox(
                                            height: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        MyTextField(
                                          hintText: 'first_name'.tr,
                                          controller: _firstNameController,
                                          focusNode: _firstNameFocus,
                                          nextFocus: _lastNameFocus,
                                          inputType: TextInputType.name,
                                          capitalization:
                                              TextCapitalization.words,
                                        ),
                                        SizedBox(
                                            height:
                                                Dimensions.PADDING_SIZE_SMALL),
                                        Row(children: [
                                          Text(
                                            'phone_number'.tr,
                                            style: sfRegular.copyWith(
                                                fontSize:
                                                    Dimensions.fontSizeSmall,
                                                color: Theme.of(context)
                                                    .disabledColor),
                                          ),
                                          SizedBox(
                                              width: Dimensions
                                                  .PADDING_SIZE_EXTRA_SMALL),
                                          Text('(${'non_changeable'.tr})',
                                              style: sfRegular.copyWith(
                                                fontSize: Dimensions
                                                    .fontSizeExtraSmall,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .error,
                                              )),
                                        ]),
                                        SizedBox(
                                            height: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        MyTextField(
                                          hintText: 'phone'.tr,
                                          inputType: TextInputType.phone,
                                          controller: _phoneController,
                                          isEnabled: false,
                                        ),
                                        SizedBox(
                                            height: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        Row(children: [
                                          Text(
                                            'alternative_phone'.tr,
                                            style: sfRegular.copyWith(
                                                fontSize:
                                                    Dimensions.fontSizeSmall,
                                                color: Theme.of(context)
                                                    .disabledColor),
                                          ),
                                          SizedBox(
                                              width: Dimensions
                                                  .PADDING_SIZE_EXTRA_SMALL),
                                        ]),
                                        SizedBox(
                                            height: Dimensions
                                                .PADDING_SIZE_EXTRA_SMALL),
                                        Container(
                                            decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(
                                                      Dimensions.RADIUS_SMALL),
                                              color:
                                                  Theme.of(context).cardColor,
                                            ),
                                            child: Column(children: [
                                              Row(children: [
                                                CodePickerWidget(
                                                  alignLeft: true,
                                                  onChanged: (CountryCode
                                                      countryCode) {
                                                    setState(() {
                                                      _countryDialCode =
                                                          countryCode.dialCode;
                                                    });
                                                  },
                                                  initialSelection: Get.find<
                                                          SplashController>()
                                                      .configModel
                                                      ?.country,
                                                  favorite: [
                                                    _countryDialCode ?? ''
                                                  ],
                                                  flagDecoration: BoxDecoration(
                                                      shape: BoxShape.circle),
                                                  showCountryOnly: true,
                                                  padding: EdgeInsets.zero,
                                                  showDropDownButton: true,
                                                  backgroundColor: Colors.white,
                                                  flagWidth: 40,
                                                  hideMainText: true,
                                                  textStyle: sfRegular.copyWith(
                                                    fontSize: Dimensions
                                                        .fontSizeDefault,
                                                    color: Theme.of(context)
                                                        .textTheme
                                                        .bodyMedium
                                                        ?.color,
                                                  ),
                                                ),
                                                Center(
                                                  child: Text(
                                                    _countryDialCode ?? '',
                                                    style: TextStyle(
                                                      fontSize: Dimensions
                                                          .fontSizeDefault,
                                                    ),
                                                  ),
                                                ),
                                                Expanded(
                                                    flex: 10,
                                                    child: CustomTextField(
                                                      hintText: Get.find<
                                                                  UserController>()
                                                              .userInfoModel
                                                              ?.alternativePhone ??
                                                          '',
                                                      controller:
                                                          _alternativePhoneController,
                                                      focusNode:
                                                          _alternativePhoneFocus,
                                                      inputType:
                                                          TextInputType.phone,
                                                      divider: false,
                                                      fontSize: Dimensions
                                                          .fontSizeDefault,
                                                    )),
                                              ]),
                                            ]))
                                      ]))),
                        ))),
                        !userController.isLoading
                            ? CustomButton(
                                onPressed: () => _updateProfile(userController),
                                margin: EdgeInsets.only(
                                    left: Dimensions.PADDING_SIZE_SMALL * 3.9,
                                    right: Dimensions.PADDING_SIZE_SMALL * 3.9,
                                    bottom: Dimensions.PADDING_SIZE_SMALL),
                                buttonText: 'update'.tr,
                              )
                            : Center(
                                child: CircularProgressIndicator.adaptive(
                                  backgroundColor:
                                      Theme.of(context).colorScheme.secondary,
                                ),
                              ),
                      ]),
                    ),
                  )
                : Center(
                    child: CircularProgressIndicator.adaptive(
                      backgroundColor: Theme.of(context).colorScheme.secondary,
                    ),
                  )
            : NotLoggedInScreen();
      }),
    );
  }

  void _updateProfile(UserController userController) async {
    bool isValid = false;
    String _firstName = _firstNameController.text.trim();
    String _alternativePhone = _alternativePhoneController.text.trim();
    String _numberWithCountryCode = _countryDialCode! + _alternativePhone;
    try {
      if (GetPlatform.isAndroid) {
        PhoneNumber phoneNumber =
            await PhoneNumberUtil().parse(_numberWithCountryCode);
        _numberWithCountryCode =
            '+' + phoneNumber.countryCode + phoneNumber.nationalNumber;
        isValid = true;
      } else {
        if (_alternativePhone.length == 9 &&
            (_alternativePhone.startsWith('9') ||
                _alternativePhone.startsWith('7'))) {
          isValid = true;
        }
      }
    } catch (e) {}

    if (userController.userInfoModel?.fName == _firstName &&
        userController.pickedFile == null &&
        userController.userInfoModel?.alternativePhone ==
            _alternativePhoneController.text.trim()) {
      showCustomSnackBar('change_something_to_update'.tr);
    } else if (_firstName.isEmpty) {
      showCustomSnackBar('enter_your_first_name'.tr);
    } else if (_alternativePhoneController.text.isNotEmpty && !isValid) {
      showCustomSnackBar('invalid_alternative_phone_number'.tr);
    } else {
      UserInfoModel _updatedUser = UserInfoModel(
          fName: _firstName,
          birthDate: userController.userInfoModel?.birthDate,
          alternativePhone: _numberWithCountryCode);
      ResponseModel _responseModel = await userController.updateUserInfo(
          _updatedUser, Get.find<AuthController>().getUserToken());
      if (_responseModel.isSuccess) {
        showCustomSnackBar('profile_updated_successfully'.tr, isError: false);
      } else {
        showCustomSnackBar(_responseModel.message);
      }
    }
  }
}
